using aichat.Entities;
using aichat.Services;
using Prism.Commands;
using Prism.Mvvm;
using System.Windows;

namespace aichat.ViewModels
{
    public class LoginViewModel : BindableBase
    {
        private readonly IUserService _userService;

        public LoginViewModel(IUserService userService)
        {
            _userService = userService;

            LoginCommand = new DelegateCommand(Login, CanLogin);
            SwitchToRegisterCommand = new DelegateCommand(SwitchToRegister);
            SwitchToLoginCommand = new DelegateCommand(SwitchToLogin);

            IsLoginMode = true;
        }

        private bool _isLoginMode = true;
        public bool IsLoginMode
        {
            get => _isLoginMode;
            set
            {
                SetProperty(ref _isLoginMode, value);
                LoginCommand.RaiseCanExecuteChanged();
            }
        }

        private string _username = string.Empty;
        public string Username
        {
            get => _username;
            set
            {
                SetProperty(ref _username, value);
                LoginCommand.RaiseCanExecuteChanged();
            }
        }

        private string _email = string.Empty;
        public string Email
        {
            get => _email;
            set
            {
                SetProperty(ref _email, value);
                LoginCommand.RaiseCanExecuteChanged();
            }
        }

        private string _password = string.Empty;
        public string Password
        {
            get => _password;
            set
            {
                SetProperty(ref _password, value);
                LoginCommand.RaiseCanExecuteChanged();
            }
        }

        private string _confirmPassword = string.Empty;
        public string ConfirmPassword
        {
            get => _confirmPassword;
            set
            {
                SetProperty(ref _confirmPassword, value);
                LoginCommand.RaiseCanExecuteChanged();
            }
        }

        private bool _isLoading = false;
        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        public DelegateCommand LoginCommand { get; }
        public DelegateCommand SwitchToRegisterCommand { get; }
        public DelegateCommand SwitchToLoginCommand { get; }

        public event Action<UserModel>? LoginSuccessful;
        public event Action? RegisterSuccessful;
        public event Action? ClearPasswordBoxes;

        private async void Login()
        {
            if (IsLoginMode)
            {
                await PerformLogin();
            }
            else
            {
                await PerformRegister();
            }
        }

        private async Task PerformLogin()
        {
            try
            {
                IsLoading = true;

                var isValid = await _userService.ValidateUserAsync(Username, Password);
                if (isValid)
                {
                    var user = await _userService.GetUserByUsernameAsync(Username);
                    if (user != null)
                    {
                        LoginSuccessful?.Invoke(user);
                    }
                }
                else
                {
                    MessageBox.Show("用户名或密码错误", "登录失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"登录失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                IsLoading = false;
            }
        }

        private async Task PerformRegister()
        {
            try
            {
                IsLoading = true;

                // 验证输入
                if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Email) || 
                    string.IsNullOrWhiteSpace(Password) || string.IsNullOrWhiteSpace(ConfirmPassword))
                {
                    MessageBox.Show("请填写所有必填字段", "注册失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (Password != ConfirmPassword)
                {
                    MessageBox.Show("两次输入的密码不一致", "注册失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (Password.Length < 6)
                {
                    MessageBox.Show("密码长度至少6位", "注册失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 检查用户名和邮箱是否已存在
                var existingUser = await _userService.GetUserByUsernameAsync(Username);
                if (existingUser != null)
                {
                    MessageBox.Show("用户名已存在", "注册失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                var existingEmail = await _userService.GetUserByEmailAsync(Email);
                if (existingEmail != null)
                {
                    MessageBox.Show("邮箱已被注册", "注册失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 创建新用户
                var newUser = new UserModel
                {
                    UserName = Username,
                    Email = Email,
                    Password = Password,
                    CreatedAt = DateTime.Now,
                    
                };

                var success = await _userService.CreateUserAsync(newUser);
                if (success)
                {
                    MessageBox.Show("注册成功！请登录", "注册成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    RegisterSuccessful?.Invoke();
                    SwitchToLogin();
                }
                else
                {
                    MessageBox.Show("注册失败，请重试", "注册失败", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"注册失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                IsLoading = false;
            }
        }

        private bool CanLogin()
        {
            if (IsLoginMode)
            {
                return !string.IsNullOrWhiteSpace(Username) &&
                       !string.IsNullOrWhiteSpace(Password) &&
                       !IsLoading;
            }
            else
            {
                return !string.IsNullOrWhiteSpace(Username) &&
                       !string.IsNullOrWhiteSpace(Email) &&
                       !string.IsNullOrWhiteSpace(Password) &&
                       !string.IsNullOrWhiteSpace(ConfirmPassword) &&
                       !IsLoading;
            }
           
        }

        private void SwitchToRegister()
        {
            IsLoginMode = false;
            ClearInputs();
        }

        private void SwitchToLogin()
        {
            IsLoginMode = true;
            ClearInputs();
        }

        private void ClearInputs()
        {
            Username = string.Empty;
            Email = string.Empty;
            Password = string.Empty;
            ConfirmPassword = string.Empty;
            ClearPasswordBoxes?.Invoke();
        }
    }
} 